package com.ruoyi.order.service.impl;

import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.order.domain.VerOrderItem;
import com.ruoyi.order.domain.dto.ScrollPageRequest;
import com.ruoyi.order.domain.dto.ScrollPageResponse;
import com.ruoyi.order.domain.dto.VerOrderItemDto;
import com.ruoyi.order.mapper.VerOrderItemMapper;
import com.ruoyi.order.service.IVerOrderItemService;
import com.ruoyi.product.domain.ProductSkuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单项Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-21
 */
@Service
public class VerOrderItemServiceImpl implements IVerOrderItemService {
    @Autowired
    private VerOrderItemMapper verOrderItemMapper;

    /**
     * 查询订单项
     *
     * @param id 订单项主键
     * @return 订单项
     */
    @Override
    public VerOrderItem selectVerOrderItemById(Long id) {
        return verOrderItemMapper.selectVerOrderItemById(id);
    }

    /**
     * 查询订单项列表
     *
     * @param verOrderItem 订单项
     * @return 订单项
     */
    @Override
    public List<VerOrderItem> selectVerOrderItemList(VerOrderItem verOrderItem) {
        return verOrderItemMapper.selectVerOrderItemList(verOrderItem);
    }

    /**
     * 新增订单项
     *
     * @param verOrderItem 订单项
     * @return 结果
     */
    @Override
    public int insertVerOrderItem(VerOrderItem verOrderItem) {
        Long maxId = verOrderItemMapper.selectMaxId();
        verOrderItem.setOrderItemId(maxId == null ? 1L : maxId + 1);
        verOrderItem.setIsReviewed(0);
        return verOrderItemMapper.insertVerOrderItem(verOrderItem);
    }

    /**
     * 修改订单项
     *
     * @param verOrderItem 订单项
     * @return 结果
     */
    @Override
    public int updateVerOrderItem(VerOrderItem verOrderItem) {
        return verOrderItemMapper.updateVerOrderItem(verOrderItem);
    }

    /**
     * 批量删除订单项
     *
     * @param ids 需要删除的订单项主键
     * @return 结果
     */
    @Override
    public int deleteVerOrderItemByIds(Long[] ids) {
        return verOrderItemMapper.deleteVerOrderItemByIds(ids);
    }

    /**
     * 删除订单项信息
     *
     * @param id 订单项主键
     * @return 结果
     */
    @Override
    public int deleteVerOrderItemById(Long id) {
        return verOrderItemMapper.deleteVerOrderItemById(id);
    }

    /**
     * 滚动分页查询订单项列表
     *
     * @param request 滚动分页请求
     * @return 滚动分页响应
     */
    @Override
    public ScrollPageResponse<VerOrderItem> selectVerOrderItemListByScroll(ScrollPageRequest request) {
        // 参数校验
        if (request.getPageSize() == null || request.getPageSize() <= 0) {
            request.setPageSize(20);
        }
        if (request.getPageSize() > 100) {
            request.setPageSize(100);
        }

        // 查询数据
        List<VerOrderItem> list = verOrderItemMapper.selectVerOrderItemListByScroll(
                request.getCursor(),
                request.getPageSize() + 1, // 多查询一条，用于判断是否还有更多数据
                request.getOrderBy(),
                request.getOrderDirection(),
                request.getOrderId(),
                request.getSkuId());

        // 判断是否还有更多数据
        boolean hasMore = false;
        Long nextCursor = null;

        if (list.size() > request.getPageSize()) {
            hasMore = true;
            // 移除多查询的那条数据
            list = list.subList(0, request.getPageSize());
        }

        // 设置下一页游标
        if (!list.isEmpty()) {
            VerOrderItem lastItem = list.get(list.size() - 1);
            nextCursor = lastItem.getOrderItemId();
        }

        return ScrollPageResponse.of(list, nextCursor, hasMore);
    }

    /**
     * 根据订单ID查询订单项列表
     *
     * @param orderId 订单ID
     * @return 订单项列表
     */
    @Override
    public VerOrderItemDto selectVerOrderItemByOrderId(Long orderId) {
        List<VerOrderItemDto> flatRows = verOrderItemMapper.selectVerOrderItemByOrderId(orderId);
        if (flatRows == null || flatRows.isEmpty()) {
            return null;
        }
        VerOrderItemDto dto = new VerOrderItemDto();
        dto.setOrderId(flatRows.get(0).getOrderId());
        dto.setUserId(flatRows.get(0).getUserId());
        dto.setAddressId(flatRows.get(0).getAddressId());
        dto.setTotalAmount(flatRows.get(0).getTotalAmount());
        dto.setDiscountType(flatRows.get(0).getDiscountType());
        dto.setShipMethod(flatRows.get(0).getShipMethod());
        dto.setPayAmount(flatRows.get(0).getPayAmount());
        dto.setFreight(flatRows.get(0).getFreight());
        dto.setStatus(flatRows.get(0).getStatus());
        dto.setPayTime(flatRows.get(0).getPayTime());
        dto.setShipTime(flatRows.get(0).getShipTime());
        dto.setReceiveTime(flatRows.get(0).getReceiveTime());

        // 使用Map来合并相同SKU的数据，收集所有URL
        Map<Long, VerOrderItem> itemMap = new LinkedHashMap<>();
        Map<Long, ProductSkuVo> skuMap = new LinkedHashMap<>();

        for (VerOrderItemDto row : flatRows) {
            if (row.getOrderItemId() != null) {
                Long skuId = row.getSkuId();

                // 处理订单项
                VerOrderItem item = itemMap.get(row.getOrderItemId());
                if (item == null) {
                    item = new VerOrderItem();
                    item.setOrderItemId(row.getOrderItemId());
                    item.setOrderId(dto.getOrderId());
                    item.setItemSkuId(row.getSkuId());
                    if (row.getQuantity() != null)
                        item.setQuantity(row.getQuantity().longValue());
                    if (row.getUnitPrice() != null)
                        item.setUnitPrice(row.getUnitPrice());
                    if (row.getTotalPrice() != null)
                        item.setTotalPrice(row.getTotalPrice());

                    item.setSkus(new java.util.ArrayList<>());
                    itemMap.put(row.getOrderItemId(), item);
                }

                // 处理SKU数据
                if (row.getSpuId() != null) {
                    ProductSkuVo skus = skuMap.get(skuId);
                    if (skus == null) {
                        skus = new ProductSkuVo();
                        skus.setId(row.getSkuId());
                        skus.setSpuId(row.getSpuId());
                        skus.setCode(row.getCode());
                        skus.setCategoryId(row.getCategoryId());
                        skus.setSpecData(row.getSpecData());
                        skus.setPrice(row.getPrice());
                        skus.setOriginalPrice(row.getOriginalPrice());
                        skus.setSkuName(row.getSkuName());
                        skus.setDescription(row.getDescription());
                        skus.setStatus(row.getSkuStatus());
                        skus.setStock(row.getStock());
                        skus.setLowStock(row.getLowStock());
                        skus.setWeight(row.getWeight());
                        skus.setVolume(row.getVolume());
                        skus.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(row.getSpecNameGroup()));
                        skus.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(row.getSpecValueGroup()));
                        skus.setUrl(row.getUrl());
                        skus.setUrls(new java.util.ArrayList<>());

                        skuMap.put(skuId, skus);
                    }

                    // 收集所有URL
                    if (row.getUrl() != null && !row.getUrl().isEmpty()) {
                        if (!skus.getUrls().contains(row.getUrl())) {
                            skus.getUrls().add(row.getUrl());
                        }
                    }
                }
            }
        }

        // 将SKU数据添加到对应的订单项中
        ArrayList<VerOrderItem> items = new ArrayList<>();
        for (VerOrderItem item : itemMap.values()) {
            Long skuId = item.getItemSkuId();
            ProductSkuVo skus = skuMap.get(skuId);
            if (skus != null) {
                item.getSkus().add(skus);
            }
            items.add(item);
        }

        dto.setOrderItems(items);
        return dto;
    }

}
